//后台数据修改
import React, { useEffect, useState } from "react";
import { Table, Button, Modal, Tooltip } from "antd";
import HTModifyConfig from "@/pages/ht-config/ht-modify-config";
import type { LocalStorageDataType } from "@/tool/type";
import type { ColumnsType } from "antd/es/table";
import { formatRange } from "@/tool/format";

const App: React.FC = () => {
  const [data, setData] = useState<LocalStorageDataType[]>([]);
  const [editItem, setEditItem] = useState<LocalStorageDataType | null>(null);
  const [modalOpen, setModalOpen] = useState(false);
  const [imgPreview, setImgPreview] = useState<{
    visible: boolean;
    url: string;
  }>({ visible: false, url: "" });

  // 读取 localStorage 数据
  const refreshData = () => {
    const list = JSON.parse(localStorage.getItem("crowdFundingList") || "[]");
    setData(list);
  };

  useEffect(() => {
    refreshData();
    // 定时监听 localStorage 变化
    const lastStr = {
      current: localStorage.getItem("crowdFundingList") || "[]",
    };
    const timer = setInterval(() => {
      const nowStr = localStorage.getItem("crowdFundingList") || "[]";
      if (nowStr !== lastStr.current) {
        lastStr.current = nowStr;
        refreshData();
      }
    }, 1500); // 每1.5秒检查一次
    return () => clearInterval(timer);
  }, []);

  // 删除操作
  const handleDelete = (id: string) => {
    Modal.confirm({
      title: "确认删除？",
      onOk: () => {
        const list = data.filter((item) => item.id !== id);
        localStorage.setItem("crowdFundingList", JSON.stringify(list));
        setData(list);
      },
    });
  };

  // 修改操作
  const handleEdit = (item: LocalStorageDataType) => {
    setEditItem(item);
    setModalOpen(true);
  };

  // 保存修改
  const handleSave = (newItem: LocalStorageDataType) => {
    const list = data.map((item) => (item.id === newItem.id ? newItem : item));
    localStorage.setItem("crowdFundingList", JSON.stringify(list));
    setData(list);
    setModalOpen(false);
    setEditItem(null);
  };

  const columns: ColumnsType<LocalStorageDataType> = [
    {
      title: "标题",
      dataIndex: "title",
      key: "title",
      width: 120,
      ellipsis: true,
      align: "center", // 新增
    },
    {
      title: "特色图",
      dataIndex: "img_link",
      key: "img_link",
      width: 80,
      align: "center",
      render: (url: string) => (
        <Tooltip title="点击查看大图">
          <img
            src={url}
            alt="特色图"
            style={{
              width: 48,
              height: 48,
              objectFit: "cover",
              borderRadius: 8,
              cursor: "pointer",
              transition: "transform 0.2s",
            }}
            onClick={() => setImgPreview({ visible: true, url })}
            onMouseOver={(e) =>
              (e.currentTarget.style.transform = "scale(1.15)")
            }
            onMouseOut={(e) => (e.currentTarget.style.transform = "scale(1)")}
          />
        </Tooltip>
      ),
    },
    {
      title: "链接",
      dataIndex: "link",
      key: "link",
      width: 120,
      align: "center",
      render: (link: string) =>
        link ? (
          <a href={link} target="_blank">
            查看
          </a>
        ) : (
          "-"
        ),
    },
    {
      title: "单价",
      dataIndex: "price",
      key: "price",
      width: 80,
      align: "center", // 修改
      render: (v: number) => `${v}¥`,
    },
    {
      title: "目标金额",
      dataIndex: "target_value",
      key: "target_value",
      width: 100,
      align: "center", // 修改
      render: (v: number) => `${v}¥`,
    },
    {
      title: "已支持人数",
      dataIndex: "supported",
      key: "supported",
      width: 100,
      align: "center",
    },
    {
      title: "状态",
      dataIndex: "status",
      key: "status",
      width: 80,
      align: "center",
      render: (v: number) => (
        <span
          style={{ color: v === 1 ? "#52c41a" : "#bfbfbf", fontWeight: 500 }}
        >
          {v === 1 ? "进行中" : "已结束"}
        </span>
      ),
    },

    {
      title: "简介",
      dataIndex: "description",
      key: "description",
      width: 180,
      ellipsis: true,
      align: "left", // 新增
      // 设置表格内容字体大小为12px
      onCell: () => ({
        style: {
          fontSize: "12px",
          whiteSpace: "pre-wrap",
          wordBreak: "break-all",
        },
      }),
    },
    {
      title: "时间段",
      dataIndex: "time",
      key: "time",
      width: 180,
      render: formatRange,
      align: "center", // 新增
      // 设置表格内容字体大小为12px
      onCell: () => ({
        style: { fontSize: "12px" },
      }),
    },
    {
      title: "操作",
      key: "action",
      width: 120,
      align: "center",
      render: (_: any, record: LocalStorageDataType) => (
        <div style={{ display: "flex", justifyContent: "center", gap: 8 }}>
          <Button type="link" size="small" onClick={() => handleEdit(record)}>
            修改
          </Button>
          <Button
            type="link"
            size="small"
            danger
            onClick={() => handleDelete(record.id)}
          >
            删除
          </Button>
        </div>
      ),
    },
  ];

  return (
    <>
      {/* 表格展示 */}
      <Table
        columns={columns}
        dataSource={data.map((item) => ({ ...item, key: item.id }))}
        style={{ marginTop: 32 }}
        pagination={false}
        bordered
        size="middle"
        rowClassName={(_, idx) =>
          idx % 2 === 0 ? "table-row-light" : "table-row-dark"
        }
        scroll={{ x: "max-content" }}
      />
      <HTModifyConfig
        open={modalOpen}
        item={editItem}
        onSave={handleSave}
        onCancel={() => setModalOpen(false)}
      />
      {/* 图片预览弹窗 */}
      <Modal
        open={imgPreview.visible}
        footer={null}
        onCancel={() => setImgPreview({ visible: false, url: "" })}
        centered
      >
        <img src={imgPreview.url} alt="大图" style={{ width: "100%" }} />
      </Modal>
      <style>{`
        .ant-table-thead > tr > th {
          font-weight: bold;
          text-align: center !important;
        }
        .ant-table-tbody > tr > td {
          vertical-align: middle;
        }
        .table-row-light {
          background: #fafbfc;
        }
        .table-row-dark {
          background: #fff;
        }
      `}</style>
    </>
  );
};

export default App;
